package com.toutiao.issue

import java.util.Calendar
import java.util.Date
import java.text.SimpleDateFormat

import java.io.PrintWriter

import scala.io.Source

object SimpleDate {
  
  private
  val X = new ThreadLocal[SimpleDateFormat]() {
    override
    def initialValue() = {
       new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
    }
  }
  
  //private
  //val M = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
  
  def format(T:Date):String = {
    X.get.format(T)
  }
  
  def getDefault = {
    X.get.parse("2015-01-01 00:00:00")
  }
  
  def parse(T:String):Date = {
    X.get.parse(T)
  }
  
  def parse(T:Long):Date = {
    //val x = X.get
    val x = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
    val y = x.format(T)
    //println(y)
    x.parse(y)
  }
  
  def current = 
    Calendar.getInstance.getTime
 
  def increment(T:Date, n:Int) = {
    val C = Calendar.getInstance
    C.setTime(T)
    C.add(Calendar.MINUTE,n)
    C.getTime
  }
  
  def sIncrement(T:Date, n:Int) = {
    val C = Calendar.getInstance
    C.setTime(T)
    C.add(Calendar.SECOND,n)
    C.getTime
  }
  
  def initDate(location:String) {
    val T = SimpleDate.current
    val line = SimpleDate.format(T)
    val F = new PrintWriter(location)
    F.write(line)
    F.close
  }
  
  def loadDate(location:String):Date = {
    val source = Source.fromFile(location,"UTF-8")
    val line = source.mkString
    SimpleDate.parse(line)
  }
  
  def saveDate(T:Date, location:String) {
    val line = SimpleDate.format(T)
    val F = new PrintWriter(location)
    F.write(line)
    F.close
  }
}


